import topology_engineer, traffic_engineer, network_controller, path_selector, traffic_history_reader, traffic_pb2
from aurora_network import *
import matplotlib.pyplot as plt
import pgfplotter_util

def tapering_to_filename(tapering):
	taper_str = "{:.3f}".format(tapering)
	taper_str = taper_str.replace('.', 'p')
	return taper_str

def main(dcn_name, block_params, tapering_factors):

	# Step 1 : Read Traffic snapshots and also build the topologies
	print("Reading traffic snapshot history from files\nDCN name:{}\n".format(dcn_name))
	block_names_list, traffic_snapshots = traffic_history_reader.TrafficSnapshotReader(dcn_name).get_traffic_snapshots()
	traffic_snapshots_timestamps = [x.time_info.start_time for x in traffic_snapshots]
	print("Reading traffic files: COMPLETE.......\n")
	print("First snapshot timestamp: {}".format(traffic_snapshots_timestamps[0]))
	total_num_snapshots = len(traffic_snapshots)
	
	# Step 2 : Contruct the physical network itself
	aurora_network = AuroraNetwork(dcn_name, block_params, block_names_list)
	netcontroller = network_controller.NetworkController(aurora_network, None, None, total_num_snapshots)

	for tapering_factor in tapering_factors:
		assert(tapering_factor > 0 and tapering_factor <= 1)

	for tapering_factor in tapering_factors:
		print("Evaluating timeseries for Fattree with tapering : {}".format(tapering_factor))
		fattree_ecmp_perf_tuples = netcontroller.evaluate_fattree_ecmp_performance(traffic_snapshots, tapering=tapering_factor)
		tapering_filename = tapering_to_filename(tapering_factor)
		pgfplotter_util.export_timeseries_performance("results/{}/timeseries_fattree_ecmp_taper{}".format(dcn_name, tapering_filename), 
														traffic_snapshots_timestamps, 
														fattree_ecmp_perf_tuples)
	return

if __name__ == "__main__":
	print("\n\n")
	print("############################################")
	print("# Simulation begins")
	print("############################################")

	### Stipulating the simulation parameters here
	#dcn_name = "ju2_dls03"
	dcn_name = "ju1_dls08"
	tapering_factors = [1., 0.8, 0.6, 0.5, 0.2, 0.1]
	#tapering_factors = [1./4]
	superblock_num_links = 256
	border_router_num_links = 256
	superblock_link_capacity = 100
	border_router_link_capacity = 100

	block_params = {BlockType.SUPERBLOCK : {}, BlockType.BORDER_ROUTER : {}}
	block_params[BlockType.SUPERBLOCK]["link capacity"] = float(superblock_link_capacity)
	block_params[BlockType.SUPERBLOCK]["num links"] = float(superblock_num_links)
	block_params[BlockType.BORDER_ROUTER]["link capacity"] = float(border_router_link_capacity) # in gbps
	block_params[BlockType.BORDER_ROUTER]["num links"] = float(border_router_num_links)

	main(dcn_name, block_params, tapering_factors)
	print("############################################")
	print("# Simulation completes")
	print("############################################")
	print("\n\n")
